<route lang="json5">
{
  style: {
    navigationBarTitleText: '羁押必要性审查',
    navigationBarTextStyle: 'white', //标题栏字体颜色
    navigationBarBackgroundColor: '#0063AF', //标题栏背景色(纯色)
  },
}
</route>
<template>
  <view class="petitioneSub bg-#F4F5F9 p-30rpx w-screen h-screen box-border overflow-auto">
    <wd-form ref="form" :model="model" :rules="rules">
      <view class="mb-20rpx rounded-20rpx overflow-hidden">
        <wd-picker
          label="主体身份"
          placeholder="请选择主体身份"
          label-width="100px"
          prop="applicantType"
          v-model="model.applicantType"
          :columns="promotionlist"
        />
      </view>
      <view class="mb-20rpx">
        <view class="text-#878787 pb-20rpx">申请人信息</view>
        <view class="rounded-20rpx overflow-hidden">
          <wd-input
            label="姓名"
            label-width="100px"
            prop="applicant"
            clearable
            v-model="model.applicant"
            placeholder="请输入姓名"
          />

          <wd-input
            label="手机号码"
            label-width="100px"
            prop="applicantPhone"
            clearable
            v-model="model.applicantPhone"
            placeholder="请输入手机号码"
          />
          <wd-input
            label="关系描述"
            label-width="100px"
            prop="content"
            clearable
            v-model="model.content"
            placeholder="请输入关系描述"
          />
        </view>
      </view>
      <view class="mb-20rpx">
        <view class="text-#878787 pb-20rpx">信访人身份证</view>
        <view class="rounded-20rpx w-100% overflow-hidden flex gap-20rpx">
          <view class="flex-1 overflow-hidden box-border">
            <wd-cell title-width="0rpx" prop="idCardUrl1">
              <image
                v-if="model.idCardUrl1 == ''"
                class="w-280rpx h-150rpx"
                src="../../../static/menu/portrait.png"
                mode="scaleToFill"
                @click="chooseAndUploadImage('idCardUrl1')"
              />
              <image
                v-else
                class="w-280rpx h-150rpx"
                :src="baseurl + model.idCardUrl1"
                mode="scaleToFill"
              />
            </wd-cell>
          </view>
          <view class="flex-1 overflow-hidden box-border">
            <wd-cell class="flex-1" title-width="0rpx" prop="idCardUrl2">
              <image
                v-if="model.idCardUrl2 == ''"
                class="w-280rpx h-150rpx"
                src="../../../static/menu/emblem.png"
                mode="scaleToFill"
                @click="chooseAndUploadImage('idCardUrl2')"
              />
              <image
                v-else
                class="w-280rpx h-150rpx"
                :src="baseurl + model.idCardUrl2"
                mode="scaleToFill"
              />
            </wd-cell>
          </view>
        </view>
      </view>
      <view class="mb-20rpx">
        <view class="text-#878787 pb-20rpx">被申请人信息</view>
        <view class="rounded-20rpx overflow-hidden">
          <wd-input
            label="姓名"
            label-width="100px"
            prop="partyName"
            clearable
            v-model="model.partyName"
            placeholder="请输入姓名"
          />

          <wd-input
            label="身份证号"
            label-width="100px"
            prop="partyCard"
            clearable
            v-model="model.partyCard"
            placeholder="请输入身份证号"
          />
        </view>
      </view>
      <view class="mb-20rpx">
        <view class="text-#878787 pb-20rpx">申请书：</view>
        <view class="rounded-20rpx p-20rpx box-border bg-#fff overflow-hidden">
          <wd-cell title-width="0rpx" prop="fileList">
            <!-- <wd-upload
              :file-list="model.fileList"
              multiple
              name="file"
              image-mode="aspectFill"
              :action="actions"
              @change="handleFileChange"
              @success="handleChange"
              class="bg-#fff"
            ></wd-upload> -->

            <wd-button size="small" icon="backtop" @click="handleFile">选择文件</wd-button>
            <view>
              <view v-for="(item, index) in model.fileList" :key="index">
                <text class="mr-10rpx my-20rpx">{{ item.name }}</text>
                <wd-icon
                  name="delete"
                  size="18px"
                  color="#ec2828"
                  @click="handleDelete(index)"
                ></wd-icon>
              </view>
            </view>
          </wd-cell>
        </view>
      </view>
      <view class="footer">
        <wd-button class="bg-#0A4484" type="primary" size="large" @click="submitHandler" block>
          提交
        </wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script setup lang="ts">
import { FormRules } from 'wot-design-uni/components/w-d-form/src/types'
import { postDetentionAPI } from '@/service/index/foo'
import { useUserStore } from '@/store'
import _ from 'lodash'
import { useToast } from 'wot-design-uni'

const userStore = useUserStore()
const model = reactive<{
  applicant: string
  partyCard: string
  applicantPhone: string
  content: string
  partyName: string
  applicantType: string
  files: string[]
  fileList: []
  status: number
  idCardUrl1: string
  idCardUrl2: string
  businessType: string
  // roleId: number
}>({
  applicantType: '',
  applicant: '',
  partyName: '',
  partyCard: '',
  idCardUrl1: '',
  idCardUrl2: '',
  applicantPhone: '',
  content: '',
  fileList: [],
  files: [],
  status: 1,
  businessType: 'jiYa',
  // roleId: userStore.userInfo.zhuanId,
})
const toast = useToast()
const form = ref()
const rules: FormRules = {
  applicant: [
    {
      required: true,
      message: '请输入申请人姓名',
      pattern: /^[\u4e00-\u9fa5]+$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入申请人姓名')
        }
      },
    },
  ],
  partyName: [
    {
      required: true,
      message: '请输入被申请人姓名',
      pattern: /^[\u4e00-\u9fa5]+$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入被申请人姓名')
        }
      },
    },
  ],
  idCardUrl1: [
    {
      required: true,
      message: '请选择身份证正面',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请选择身份证正面')
        }
      },
    },
  ],
  idCardUrl2: [
    {
      required: true,
      message: '请选择身份证背面',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请选择身份证背面')
        }
      },
    },
  ],
  content: [
    {
      required: true,
      message: '请输入关系描述',
      pattern: /^[\u4e00-\u9fa5]+$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入关系描述')
        }
      },
    },
  ],
  partyCard: [
    {
      required: true,
      message: '请输入正确的身份证号',
      pattern: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\d|X|x]$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入身份证号')
        }
      },
    },
  ],
  applicantPhone: [
    {
      required: true,
      message: '请输入正确的手机号',
      pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入手机号')
        }
      },
    },
  ],
  fileList: [
    {
      required: true,
      message: '请选择活申请书',
      validator: (value) => {
        if (Array.isArray(value) && value.length) {
          return Promise.resolve()
        } else {
          return Promise.reject()
        }
      },
    },
  ],
}
const fileList = ref<any[]>([])
const promotionlist = ref<any[]>([
  {
    value: '1',
    label: '当事人',
  },
  {
    value: '2',
    label: '当事人法定代理人',
  },
  {
    value: '3',
    label: '当事人近亲属',
  },
  {
    value: '4',
    label: '辩护人',
  },
])
const baseurl = import.meta.env.VITE_SERVER_BASEURL
const actions: string = baseurl + '/app-api/infra/file/upload-id'
const action: string = baseurl + '/app-api/infra/file/upload'
onLoad((options) => {})
function handleChange({ file }) {
  const { data } = JSON.parse(file.response)
  model.files.push(data)
}
function handleFileChange({ fileList }) {
  model.fileList = fileList
}
function chooseAndUploadImage(type) {
  // 选择图片
  uni.chooseImage({
    count: 1, // 默认9，设置图片的数量
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: (chooseImageRes) => {
      const tempFilePaths = chooseImageRes.tempFilePaths
      toast.loading({
        msg: '识别中...',
      })
      uni.uploadFile({
        url: '/app-api/send/IdCard', // 开发者服务器的URL
        filePath: tempFilePaths[0],
        name: 'file', // 必填，文件对应的 key
        success: (res) => {
          const { code } = JSON.parse(res.data)
          console.log(code, 111111)
          if (code != 500) {
            uni.uploadFile({
              url: '/app-api/infra/file/upload', // 开发者服务器的URL
              filePath: tempFilePaths[0],
              name: 'file', // 必填，文件对应的 key
              success: (res) => {
                const { data } = JSON.parse(res.data)
                if (type == 'idCardUrl1') {
                  model.idCardUrl1 = data
                } else {
                  model.idCardUrl2 = data
                }
                toast.close()
                toast.success({
                  msg: '识别成功',
                })
              },
              fail: (uploadFileErr) => {
                toast.close()
                toast.error({
                  msg: '识别失败，重新上传',
                })
                console.error('upload fail:', uploadFileErr)
              },
            })
          } else {
            toast.error({
              msg: '识别失败，重新上传',
            })
          }
        },
        fail: (uploadFileErr) => {
          toast.error({
            msg: '识别失败，重新上传',
          })
          console.error('upload fail:', uploadFileErr)
        },
      })
    },
    fail: (chooseImageErr) => {
      console.error('choose image fail:', chooseImageErr)
    },
  })
}
const submitHandler = _.debounce(() => {
  handleSubmit()
}, 1000)
function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        try {
          postDetentionAPI({
            ...model,
            fileList: undefined,
            files: [...model.files],
            openId: userStore.userInfo.openid,
          }).then((res) => {
            if (res.code == 0) {
              toast.success({
                msg: '操作成功',
                duration: 0,
              })
            } else {
              toast.error({
                msg: res.msg,
                duration: 0,
              })
            }

            setTimeout(() => {
              uni.navigateBack()
              toast.close()
            }, 1500)
          })
        } catch (error) {
          console.log(error)
        }
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
function handleDelete(index) {
  model.fileList.splice(index, 1)
  model.files.splice(index, 1)
}
function handleFile() {
  wx.chooseMessageFile({
    count: 1, // 限制选择的文件数量
    type: 'file', // 非图片和视频的文件,不选默认为all
    extension: ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx'], // 此处限制文件类型
    // extension: ['xls', 'xlsx'], //此处限制文件类型
    success(res) {
      const tempFilePaths = res.tempFiles
      toast.loading({
        msg: '上传中...',
      })
      // 下面是返回后需要调接口的操作
      const uploadTask = uni.uploadFile({
        url: '/app-api/infra/file/upload-id',
        filePath: tempFilePaths[0].path,
        method: 'POST',
        name: 'file',
        formData: {
          name: tempFilePaths[0].name,
        },
        success: (uploadFileRes) => {
          // 接口返回的数据
          model.fileList.push(tempFilePaths[0])
          const { data } = JSON.parse(uploadFileRes.data)
          model.files.push(data)
        },
        fail: () => {
          toast.close()
        },
      })
      uploadTask.onProgressUpdate((res) => {
        toast.loading({
          msg: '上传中' + res.progress + '%',
        })
        if (res.progress == 100) {
          toast.close()
        }
      })
    },
  })
}
</script>
<style lang="scss" scoped>
::v-deep .wd-upload {
  background: #fff;
}

::v-deep .wd-cell {
  padding-left: 0rpx !important;
}

::v-deep .wd-cell__wrapper {
  padding: 10rpx !important;
}

::v-deep .wd-cell__left {
  margin-right: 5rpx !important;
}

::v-deep .wd-cell__value {
  text-align: left !important;
}
</style>
